<template>
  <base-breadcrumb :title="$route.meta.title" :breadcrumb="!isAudit">
    <!-- 技术服务需求编辑 -->
    <a-form-model class="updateServiceDemand"
      ref="ruleForm"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel == 0 ? {} : rules"
    >
      <a-spin :spinning="loading">
        <!-- 表单 -->
        <a-card :bordered="false">
          <title-name title="基本信息"></title-name>
          <custom-form :formList="formList" :form="form" :is-emit="false" :editModel="editModel == 0 ? '' : ''" @selectOrg="selectOrg">
            <!-- 附件上传 -->
            <template #fileInfoList>
              <template v-if="editModel != 0">
                <l-table businessCode="FACE14" :uploadArrys.sync="form.fileInfoList"></l-table>
              </template>
              <file-link v-else :fileList="form.fileInfoList" style="margin-top: -3px"></file-link>
            </template>
            <template #photo>
              <div v-if="editModel == 0 && (!form.photo || form.photo.length < 1)" style="margin-top: -3px;margin-left: 134px;">
                无
              </div>
              <l-table
                v-else
                uploadType="image"
                businessCode="FACE14"
                :disabled="editModel == 0"
                :editModel="editModel"
                :uploadArrys.sync="form.photo"
                multiple
              ></l-table>
            </template>
          </custom-form>
        </a-card>
        <!-- 页脚操作栏 -->
        <div class="btn_box page-btn-right-top" v-if="editModel != 0 && !isConsultation">
          <a-button
            class="button_right"
            v-if="form.status == 'REJECTED'"
            type="primary"
            :loading="loadingBtn.REJECTED"
            @click="handleSubmit('REJECTED')"
            >保存</a-button
          >
          <a-button
            v-else
            class="button_right"
            type="primary"
            :loading="loadingBtn.DRAFT"
            @click="handleSubmit('DRAFT')"
            >保存草稿</a-button
          >
          <a-button
            class="button_right"
            type="primary"
            :loading="loadingBtn.SUBMITTED"
            @click="handleSubmit('SUBMITTED')"
            >提交</a-button
          >
          <a-button @click="handleActiveClose">关闭</a-button>
        </div>
         <div class="btn_box page-btn-right-top" v-else-if="!isConsultation">
          <BasePrintButton
            class="button_right"
            v-if="!isAudit && form.auditStatus*1 === 3"
            type="primary"
            :beforePrintFn="print"
          />
        <a-button  @click="handleActiveClose">关闭</a-button>
      </div>
      </a-spin>
    </a-form-model>
     <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import { updateByPrimaryKeySelective,addInsertSelective,technicalServiceNeedsPrint,getTechnicalServiceNeedsByIdDetail} from '@/api/technical/serviceDemand'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import BSelect from '@/components/BComponents/BSelect'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司项目
import ASelectOrgPeople from '@/components/Select/ASelectOrgPeople' //联系人项目加岗位
import {technicalServiceType } from './model'
import { isPhone,createValidator} from '@/utils/regExpression.js'
export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    SelectProject,
    BSelect,
    SelectSubCompany,
    ASelectOrgPeople,
  },
  data() {
    return {
      loading: false, // 加载控件
      visible: false, //人员选择控件
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
      form: {branchComName:'',branchComId:null,projectName:'',projectId:null,linkmanPost:'',curId: "",type:'0'}, // 表单
      id: '',
      curOrg:null,
      loadingBtn: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false,
        REJECTED: false
      },
      rules: {
        name: [{ required: true, message: '请输入技术服务名称', trigger: 'blur' },{ min: 1, max: 20, message: '长度不得超过20字', trigger: 'blur' }],
        place: [{ required: true, message: '请输入地点', trigger: 'blur' },],
        overallSituation: [{ required: true, message: '请输入整体概况', trigger: 'blur' },],
        content: [{ required: true, message: '请输入技术服务需求内容', trigger: 'blur' },],
        fileInfoList: [{ type: 'array', required: true, message: '请上传附件', trigger: 'blur' }],
        linkmanId: [{ required: true, message: '请选择联系人', trigger: 'change' }],
        monitoringTime: [{ required: true, message: '请选择时间', trigger: 'change' }],
        phone: [
          { required: true, message: '请输入联系人手机', trigger: 'blur' },
          { validator: createValidator(isPhone, '请输入正确的手机号'), trigger: 'blur' },
        ],
      }, // 校验规则
      init: false, // 初始化控件
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  props: {
    // 是否作为审批详情
    isAudit: {
      type: Boolean,
      default: false
    },
    // 是否作为意见征询
    isConsultation: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    // 监听附件实现附件校验
    'form.fileInfoList'() {
      if (this.editModel != 0 && this.init) {
        this.$nextTick(() => {
          this.$refs.ruleForm?.validateField('fileInfoList')
        })
      }
    },
    // 监听照片实现照片校验
    'form.photo'() {
      if (this.editModel != 0 && this.init) {
        this.$nextTick(() => {
          this.$refs.ruleForm?.validateField('photo')
        })
      }
    },
    'form.projectId'(val){
      this.form.type = val? '1':'0'; //有项目就是项目技术服务，反之业务管控服务
    },
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            this.editModel = 0
          })
        }
      }
    }
    },
  async mounted() {
    // this.editModel*1===2 && this.getLoginInfo();
      this.curOrg = this.ownOrgList.find((v) => {
          return v.id == this.curTagCode
        })
     if(!this.curOrg){   //如果找到，就新增一条
          this.ownOrgList.push({
            code:this.$currentPost().code,
            id:this.$currentPost().orgId,
            name:this.$currentPost().orgName
          })
        }
        this.form.branchComId = this.curOrg?.id || this.curTagCode
        this.form.curId = this.$currentPost().id
    if ( this.editModel*1!== 2) {
         await this.getDetailData();

      }
    this.$route.meta.title = ['技术服务需求 查看', '技术服务需求 编辑', '技术服务需求 新增'][this.editModel]
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('technical_service_needs_audit')

  },
  computed: {
    curTagCode() {
        return this.$currentPost().orgId
      },
      ownOrgList() {
        let levels = [...this.$userInfo().employee.levels]
        let ownOrg = levels.filter((v) => {
          return v.code === 'CO' || v.code === 'BC'
        })
        ownOrg.forEach((v) => {
          if (v.code == 'CO') v.name = '总部机关'
        })
        return ownOrg
      },
    formList() {
      return [
        {
          label: '所属单位',
          type: 'orgTree',
          keyName: 'curId',
          rules: [{ required: true, message: '请选择', trigger: 'change' }],
          span: 16,
          isAutoSelectFirst:true,
          isNeedAuth:true,
          checkStrictly: false,
          disabled: true,
          needTags: ['CO', "BC", "PD"],
          isQueryProjecDetail: false
        },
          // {
          //   type: 'a-select',
          //   keyName: 'branchComId',
          //   label: '所属组织机构',
          //   data: this.ownOrgList,
          //   disabled:true,
          //   replaceFields: {
          //     label: 'name',
          //     value: 'id'
          //   },
          //   change: (e) => {
          //   }
          // },
          // {
          //   type: SelectProject,
          //   keyName: 'projectId',
          //   viewName: 'projectName',
          //   label: '所属项目',
          //   disabled: true,
          //   attrs: {
          //     isDefaultSelected: this.editModel == 2,
          //     autoSelected: this.editModel == 2,
          //     keyValue: 'branchComId',
          //     isClear: this.editModel == 2,
          //     isEdit: this.editModel != 2,
          //     isSelf:false,
          //     form: this.form
          //   },
          //   selectChange: (e) => {
          //     console.log(e)
          //   }
          // },
        {
          keyName: 'name',
          type: 'BaseInput',
          disabled: this.editModel == 0,
          label: '技术服务名称',
          placeholder: '不超过20字',
         },
        {
          keyName: 'monitoringTime',
          type: 'a-range-picker',
          placeholder: ['请选择日期', '请选择日期'],
          disabled: this.editModel == 0,
           label: '时间',
            attrs: {
                valueFormat: 'YYYY-MM-DD'
            }
        },
        {
          keyName: 'place',
          type: 'BaseInput',
          disabled: this.editModel == 0,
          label: '地点',
         },
        {
          keyName: 'type',
          type: 'a-select',
          disabled:true,
          label: '技术服务类型',
          data: technicalServiceType,
        },
        // {
        //   type: SelectPersonByProject,
        //   keyName: 'makeUserId',
        //   disabled: this.editModel == 0,
        //   label: '联系人',
        //   attrs: {
        //       branchComId:this.form.branchComId,
        //       isOrg: true,
        //       showSearch: true,
        //       addJob: true
        //   }
        //   },
          {
          keyName: 'linkmanId',
          viewName: 'mainPeopleName',
          type: ASelectOrgPeople,
         disabled: this.editModel == 0,
          label: '联系人',
          attrs: {
            keyValue: 'branchComId',
            init: false,
          },
          onSelectChange: (e) => {
            this.$set(this.form, 'linkmanPost', e.name)
          }
        },
        {
          keyName: 'phone',
          type: 'BaseInput',
          disabled: this.editModel == 0,
          label: '联系人手机',
         },
        {
          keyName: 'overallSituation',
          type: 'BaseTextarea',
          disabled: this.editModel == 0,
          label: '整体概况',
          span: 24,
        },
        {
          keyName: 'content',
          type: 'BaseTextarea',
          disabled: this.editModel == 0,
          label: '技术服务需求内容',
          span: 24,
        },
        {
          slot: true,
          keyName: 'photo',
          label: '',
          span: 24,
          businessCode: 'FACE14',
        },
        {
          keyName: 'remark',
          type: 'BaseTextarea',
          disabled: this.editModel == 0,
          label: '备注',
          placeholder: '如果特殊情况或需求,请备注描述。',
          span: 24,
        },
        {
          slot: true,
          keyName: 'fileInfoList',
          label: '附件上传',
          span: 24,
          businessCode: 'FACE14'
        }
      ]
    }
  },
  methods: {
    selectOrg(val) {
      if(val.length === 1 || val.length === 2) {
        this.form.branchComId = val[val.length - 1].orgId
      } else if(val.length > 2) {
        this.form.branchComId = val[val.length - 2].orgId
        this.form.projectId = val[val.length - 1].projectId
      }
    },
    // getLoginInfo(){
    //   let userInfo = JSON.parse(sessionStorage.getItem('ycloud-user_info')),
    //   currentPost = userInfo?.currentPost ||{};
    //   console.log(currentPost)
    //    this.form.branchComName = currentPost.orgName;
    //    this.form.branchComId = currentPost.branchComId;
    //    if(currentPost.code === 'PD'){
    //      this.form.projectName = currentPost.name;
    //      this.form.projectId = currentPost
    //    }
    //     this.form.branchComId = userInfo.currentPost.code === 'PD' ? userInfo.currentPost.id : userInfo.currentPost.branchComId

    // },
    // 打印
    print() {
      return technicalServiceNeedsPrint({ id: this.id }).then(res => {
        return res.data.content
      })
    },
    validateForm() {
      let flag = false
      this.$refs.ruleForm.validate((e) => {
        if (e) {
          flag = true
        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
      return flag
    },
    getDetailData() {
      // 不为添加时请求详情
      if (this.editModel != 2) {
        this.loading = true
        getTechnicalServiceNeedsByIdDetail({ id: this.id })
          .then((res) => {
            this.loading = false
            if(res.data.needStartTime && res.data.needEndTime){
              res.data.monitoringTime = [res.data.needStartTime,res.data.needEndTime]
            }
            res.data.type = res.data.type.toString()
            this.form = { ...this.form, ...res.data }
            if(this.form.projectId) {
              this.form.curId = this.form.projectId
            } else {
              this.form.curId = this.form.branchComId
            }
            this.$nextTick(() => {
              this.init = true
            })
          })
          .catch(() => {
            this.loading = false
          })
      } else {
        this.$nextTick(() => {
          this.init = true
        })
      }
    },
    /**
     * 提交表单
     */
    handleSubmit(status) {
      this.setProcessConfig = null;
      if (status == 'SUBMITTED' && !this.validateForm()) {
        return
      }
      this.loading = true
      this.loadingBtn[status] = true
      let form = this.$clone(this.form)
      if(form.monitoringTime?.length){
        form.needStartTime = form.monitoringTime[0];
        form.needEndTime = form.monitoringTime[1];
      }
      if (status != 'REJECTED') {
        form.auditStatus = status == 'SUBMITTED' ? 1 : 0
      } else {
        form.auditStatus = 5
      }
      let api = [updateByPrimaryKeySelective, addInsertSelective][this.editModel - 1]
      this.submitApprovalConfirm(status == 'SUBMITTED' ? this.processConfig : 6, (flag)=>{
        if(!flag) {
          this.loading = false
          this.loadingBtn[status] = false
          return
        }
      api(form)
        .then((res) => {
          this.loading = false
          this.loadingBtn[status] = false
          this.$message.success(status == 'SUBMITTED' ? '提交成功！' : '保存成功')
          if(status =='SUBMITTED') {
            //提交时，返回id
              this.businessId = res.data.id;
              this.setProcessConfig = this.processConfig;
              return
            }else{
            this.$multiTab.close()
          }
        })
        .catch(() => {
          this.loadingBtn[status] = false
          this.loading = false
          this.$message.warning(err.data.message)
        })

      })
    }
  }
}
</script>
<style lang="less" scoped>
</style>
